<template>
  <div>
    <table class="tab">
      <tr>
        <th>序号</th>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item, index) in phone_list" :key="index">
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>
          <Button @click="minus(item)">-</Button>&nbsp; {{ item.num }}&nbsp;
          <Button @click="add(item)">+</Button>
        </td>
        <td><Button @click="del(index)" color="red">移除</Button></td>
      </tr>
      <Button @click="add_cart('汽车')">添加汽车</Button>
      <h4>总数：{{ totalCount() }}</h4>
      <h4>总价：${{ total }}</h4>
      <Button color="red">清空购物车</Button>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      phone_list: [
        { id: 1, name: "iphone8", price: 5099, num: 3 },
        { id: 2, name: "iphone xs", price: 8699, num: 1 },
        { id: 3, name: "iphone xr", price: 6499, num: 1 }
      ]
    };
  },
  //监听属性
  watch: {
    counter: function(nval, oval) {
      console.log("计数器的变化:" + "从" + oval + "变成了" + nval);
    }
  },
  //计算属性
  computed: {
    //反转
    reverse_msg: function() {
      return (
        "$" +
        this.msg
          .split("")
          .reverse()
          .join("")
      );
    },
    total() {
      let total = 0;
      for (let index = 0; index < this.phone_list.length; index++) {
        total +=
          this.phone_list[index]["price"] * this.phone_list[index]["num"];
      }
      return total;
    }
  },
  methods: {
    // 汇总商品数量
    totalCount: function() {
      // 默认值
      let totalcount = 0;
      // 遍历
      for (let i = 0, l = this.phone_list.length; i < l; i++) {
        // 累加
        totalcount += this.phone_list[i]["num"];
      }
      return totalcount;
    },
    // 增加数量
    add: function(item) {
      item.num++;
    },
    // 减少数量
    minus: function(item) {
      if (item.num > 0) {
        item.num--;
      }
    },
    // 删除
    del(index) {
      // 根据下标删除元素
      this.phone_list.splice(index, 1);
    },

    // 添加购物车方法
    add_cart: function(name) {
      // 声明购物车变量
      let cartlist = this.phone_list;
      // 声明坐标
      let find = 0;
      // 遍历购物车列表
      for (let i = 0, l = cartlist.length; i < l; i++) {
        // 判断
        if (name == cartlist[i]["name"]) {
          cartlist[i]["num"]++;
          find = 1;
          break;
        }
      }
      // 没找到
      cartlist.push({ id: 4, name: name, price: 100, num: 1 });
    }
  }
};
</script>

<style>
.tab {
  width: 700px;
  height: 200px;
  border: 1px solid #0000;
  text-align: center;
  margin: auto;
}
.tab th {
  border: 1px solid #0000;
}
.tab td {
  border: 1px solid #0000;
}
</style>